<?php
/*
*	$version: 2009-5-13 Pm 18:35:57
*	$id: common.php 
*	$author: taoFeng
*	$mailto: font99@Gmail.com
*	$license: This is not a freeware
*/
$_G['startTime'] = sprintf('%.8f',array_sum(explode(' ', microtime())));

define('SYS_DEBUG', false);
if (SYS_DEBUG) error_reporting(E_ALL); else error_reporting(0);
define('IN_LEKO', TRUE);
define('FILE_ROOT', substr(dirname(__FILE__), 0, -13) . DIRECTORY_SEPARATOR);
define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
define('CLASS_PATH', 'model' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR);
set_time_limit(300);

if (function_exists('ini_get'))
	$onOff = ini_get('register_globals');
else
	$onOff = get_cfg_var('register_globals');

if ($onOff != 1 && strtolower($onOff) != 'on') {
	@extract($_POST, EXTR_SKIP);
	@extract($_GET, EXTR_SKIP);
	$onOff = 0;
}
else
	$onOff = 1;

if(PHP_VERSION < '5.1.0') exit('PHP_VERSION < 5.1');

if (!version_compare(PHP_VERSION, '6.0.0-dev', '>=')){
	set_magic_quotes_runtime(0);
	if ($onOff) if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) exit('Request tainting attempted.');
}

function leko_addslashes($a, $f = 0) {
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $f) {
		if(is_array($a)) { foreach($a as $key => $val) { $a[$key] = leko_addslashes($val, $force); } } else {$a = addslashes($a);}
	}
	return $a;
}

function leko_htmlspecialchars($s, $isstrips = true, $nl2br = false){
	if(is_array($s)):
		foreach($s as $_k => $_v)
			$s[$_k] = leko_htmlspecialchars($_v);
	else :
		if ($isstrips) $s = stripslashes($s);
		$s = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
		str_replace(array('&', '"', '<', '>',"'",'\\',' '), array('&amp;', '&quot;', '&lt;', '&gt;','&#39;','&#92;','&nbsp;'), $s));
		if ($nl2br) $s = nl2br($s);
	endif;
	return $s;
}

function leko_head($_url,$_t = 0){
	header('Refresh: '.$_t.'; URL=' . $_url);
	echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta http-equiv="refresh" content="'.$_t.'; url=' . $_url . '"><title></title></head></html>';
	exit();
}

function leko_fileexists($_f){if (file_exists($_f)) return ($_f); else exit("<p>The " . $_f . " file could not be found.</p>");}

function leko_shutdown(){ global $_D,$_G,$_S; $_D->freeResult(); if(strcasecmp($_G['sessStorageType'],"SessionDb") == 0) {if ($_G['sessNewlink']) {$_D->dbClose();}}else {$_D->dbClose();} if(SYS_DEBUG) {new Debug();}}

function leko_language($_filename,$_type = '') {
	global $_G;
	$_languagePack = FILE_ROOT . "res/lan/" . $_G['langMeta'] . "/" . $_filename . "_" . $_type . ".lang" . $_G['phpEx'];
	if (!file_exists($_languagePack)) return false; else return $_languagePack;
}

if (!MAGIC_QUOTES_GPC) {
    $_GET = leko_addslashes($_GET);
    $_POST = leko_addslashes($_POST);
    $_COOKIE = leko_addslashes($_COOKIE);
	$_REQUEST = leko_addslashes($_REQUEST);
}

if (count($_FILES)) {$_FILES = leko_addslashes($_FILES);}

if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
	$_G['onlineIp'] = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
	$_G['onlineIp'] = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
	$_G['onlineIp'] = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
	$_G['onlineIp'] = $_SERVER['REMOTE_ADDR'];
}

preg_match("/[\d\.]{7,15}/", $_G['onlineIp'], $onlineipMatches);
$_G['onlineIp'] = $onlineipMatches[0] ? $onlineipMatches[0] : 'unknown';
unset($onlineipMatches);

//var init
$__act = $__user = $__css = $__htm = '';
$__page = 0;

foreach(array('_POST', '_GET') as $_req) {
	foreach($$_req as $_k => $_v) { if ($_k{0} != '_'){ $_k = '__' . $_k ; $$_k = leko_addslashes($_v); } }
}

$_G['phpEx'] = NULL; $_G['phpEx'] = is_string($_G['phpEx']) ? $_G['phpEx'] : strrchr(__FILE__, '.');
$_G['phpSelf'] = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$_G['baseScript'] = basename($_G['phpSelf']);
$_G['ieBrowser'] = (strpos($_SERVER['HTTP_USER_AGENT'],"MSIE") !== false )? true : false;
$_G['timeMillis'] = intval($_G['startTime']).substr(microtime(),2,3);
$_G['time'] = time();
$_G['curDate'] = date("Y-m-d",$_G['time']);
$_G['scriptFileName'] = str_replace('\\\\', '/', (isset($_SERVER['PATH_TRANSLATED']) ? $_SERVER['PATH_TRANSLATED'] : $_SERVER['SCRIPT_FILENAME']));
$_G['languageName'] = substr($_G['scriptFileName'],strlen(FILE_ROOT),- strlen($_G['phpEx']));

if(!empty($_G['loadControl']) && substr(PHP_OS, 0, 3) != 'WIN') {
	if($fp = @fopen('/proc/loadavg', 'r')) {
		list($loadaverage) = explode(' ', fread($fp, 6));
		fclose($fp);
		if($loadaverage > $_G['loadControl']) {
			header("HTTP/1.0 503 Service Unavailable");
			exit();
		}
	}
}

include(leko_fileexists(FILE_ROOT . 'config/config.inc' . $_G['phpEx'])); //config ini

include(leko_fileexists(FILE_ROOT . 'model/lib/basic.function' . $_G['phpEx']));//cache factory

include(leko_fileexists(FILE_ROOT . 'model/kernel/cacheFactory' . $_G['phpEx']));//cache factory

include(leko_fileexists(FILE_ROOT . 'model/classes/Stroage/' . $_G['dbType'] . '.class' . $_G['phpEx']));

include(leko_fileexists(leko_language('global','system')));//global language;

function __autoload($className) {
	global $_G,$_C;

	$classFile = FILE_ROOT . CLASS_PATH . $className . DIRECTORY_SEPARATOR . $className . '.class' . $_G['phpEx'];
	$key = md5($classFile);
	if (is_object($_C) && $_C->memcacheSupported === true && !function_exists('apc_cache_info')) {
		$file_content = $_C->_getCache($key);
		if (!is_array($file_content) || filemtime($classFile) > $file_content[1]) {
			$func = function_exists("php_strip_whitespace") ? "php_strip_whitespace" : "file_get_contents";
			$file_content[0] = $func($classFile);
			$_C->_setCache($key,$file_content[0]);
		}
		eval('?>' . $file_content[0] . '<?php '); 
	}
	else {
		if (!class_exists($className)) {
			if (file_exists($classFile)) {
				require $classFile;
			}
			else {
				eval('class '.$className.' extends Exception {}');
				throw new $className("[__autoload] this file doesn't exists: ".$classFile);
			}
		}
	}
}

if (!defined('STORAGEINITCLOSE')) {
	$_D = new $_G['dbType'];
	$_D->stoageInit($_G['dbHost'], $_G['dbUser'], $_G['dbPass'], $_G['dbName'], $_G['dbPort'], false) || exit("<p>Database could not be connect.</p>");
	unset($_G['dbUser'],$_G['dbPass'],$_G['dbName'],$_G['dbPort']);
}

include_once (leko_fileexists(FILE_ROOT . 'model/classes/Cache/' . $_G['cacheMs'] . '.class' . $_G['phpEx']));//cache
$cacheControl = "new" . $_G['cacheMs'];
$_C = new $cacheControl();

if (strcasecmp($_G['charSet'],'UTF-8') == 0) {$_D->Query("SET NAMES 'UTF8'");if (function_exists('mb_internal_encoding')) mb_internal_encoding($_G['charSet']);header('Content-Type: text/html; charset='.$_G['charSet']);}

$_T = new Template();

if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();

if(function_exists('date_default_timezone_set')) 
	{ date_default_timezone_set('Asia/ShangHai');$_G['timeOffset'] = 0; } else $_G['timeOffset'] = 8;

session_set_cookie_params(-1,'/',$_G['sessionCookie']);

if (strcasecmp($_G['sessStorageType'],"default") == 0) {
	session_save_path(FILE_ROOT . $_G['sessionDir']);
}
else {
	session_cache_limiter('private');
	ini_set('session.save_handler', 'user');
	$_sess = new $_G['sessStorageType']();
	session_set_save_handler(array($_sess, 'open'),
							 array($_sess, 'close'),
							 array($_sess, 'read'),
							 array($_sess, 'write'),
							 array($_sess, 'destroy'),
							 array($_sess, 'gc'));
}
@session_start();

if (!isset($_SESSION) || !is_array($_SESSION)) {
	$_SESSION = array();
}

//extern framework vars
$_G['uploadServerPrefix'] = "upload";
$_G['httpReferer'] = rawurldecode(getReferer());

$countSpaceName = preg_match("/([A-Za-z0-9-]{3,20})?{$_G['domainName']}/is", $_SERVER['HTTP_HOST'], $spaceNameMatches);
$_G['spaceName'] = ($countSpaceName > 0) ? $spaceNameMatches[1] : "www";
$_G['spaceDomain'] = "http://";
if ($_G['useSecondDomain']) {
	$_G['spaceDomain'] .= $_G['spaceName'] . $_G['domainName'];
}
else {
	if (!empty($__user)) {
		$_G['spaceDomain'] .= "www" . $_G['domainName'] . "/space/index" . $_G['phpEx'] . '?user=' . $__user;
		$_G['spaceName'] = $__user;
	}
}

$_G['cookieSet'] = array(
	'COOKIEPATH'	=>	'/',
	'COOKIEPRE'		=>	$_G['cookiePrefix'],
	'COOKIEDOMAIN'	=>	$_G['domainName'],
	'COOKIETIMEOUT'	=>	0,
	'SERVER_PORT'	=>	''
);

if (!empty($__htm)) {
	$_G['siteTplName'] = trim ($__htm);
	Cookie('siteHtmName', $_G['siteTplName'], 1, $_G['cookieSet']);
}
else {
	$_G['siteTplName'] = isset($_COOKIE[$_G['cookiePrefix'].'siteTplName']) ? $_COOKIE[$_G['cookiePrefix'].'siteTplName'] : $_G['siteTplName'];
}

if (!empty($__css)) {
	$_G['cssName'] = trim ($__css);
	Cookie('cssName', $_G['cssName'], 1, $_G['cookieSet']);
}
else {
	$_G['cssName'] = isset($_COOKIE[$_G['cookiePrefix'].'cssName']) ? $_COOKIE[$_G['cookiePrefix'].'cssName'] : $_G['cssName'];
}

if (!in_array($_G['spaceName'],$_G['holdKey'])) {
	$_T->setViewName($_G['siteTplName']);
	define('IN_SITE', FALSE);
}
else {
	$_T->setViewName($_G['wwwTplName']);
	if (strcasecmp($_G['spaceName'],"www") == 0) define("IN_SITE" , true);
	else define("IN_SITE" , FALSE);
}

$fileLanguage = leko_language($_G['languageName']);
if (!empty($fileLanguage)) {
	include ($fileLanguage);
}
$_G['pageName'] = str_replace("/","_",$_G['languageName']);

//controller
if (!empty($_G['modName'])) {
	if (strncmp($_G['modName'],"space",5) == 0) {
		if (IN_SITE === true) die();
	}
	elseif (strncmp($_G['modName'],"index",5) == 0) {
		if (IN_SITE === false) die();
	}
}

register_shutdown_function('leko_shutdown');

if (isset($__php2info)){
	phpinfo();exit;
}

?>